package com.antdesignbackend.backend.accountmanage.controller;

import java.io.Serializable;
import java.util.*;

import com.antdesignbackend.backend.accountmanage.entity.UserMenu;
import com.antdesignbackend.backend.accountmanage.service.UserMenuService;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.RoleMenuVo;
import com.antdesignbackend.backend.entity.entityVo.UserRoleVo;
import com.antdesignbackend.backend.service.RoleMenuService;
import com.antdesignbackend.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import lombok.Data;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.aop.AuthToken;

/**
 * 账号管理
 *
 * @author tang,qm
 * @email tang,qm@163.com
 * @date 2020-07-27 11:37:57
 */

@Controller
@RequestMapping("/users")
@Slf4j
public class UsersController extends BaseController{

	private static final String FUN_NAME = "账号管理";//功能名称

	@Autowired
	private UserService userService;

	@Autowired
	private UserMenuService userMenuService;

	@Autowired
	private RoleMenuService roleMenuService;

	@GetMapping("/breedIndex")
	@AuthToken
	public String breedIndex() {
		return "accountmanage/users/breedIndex";
	}


	@GetMapping("/slaughterIndex")
	@AuthToken
	public String slaughterIndex() {
		return "accountmanage/users/slaughterIndex";
	}


	@GetMapping("/harmlessIndex")
	@AuthToken
	public String harmlessIndex() {
		return "accountmanage/users/harmlessIndex";
	}


	@PostMapping("/tableSearch")
	@ResponseBody
	ReturnVO tableSearch(@RequestBody UserRoleVo usersVo) throws SecurityException, IllegalArgumentException{
		ReturnVO result = new ReturnVO();
		QueryWrapper<Users> wrapper = new QueryWrapper<>();
		wrapper.eq("Eid",this.getLoginEnterpriseId());
		wrapper.eq("Grade",2);
		if(StringUtils.isEmpty(usersVo.getUserName())==false){
			wrapper.like("UserName",usersVo.getUserName());
		}
		if(StringUtils.isEmpty(usersVo.getRealName())==false){
			wrapper.like("RealName",usersVo.getRealName());
		}
		if(StringUtils.isEmpty(usersVo.getPhone())==false){
			wrapper.like("Phone",usersVo.getPhone());
		}
		if(StringUtils.isEmpty(usersVo.getCombination())==false){
			wrapper.like("UserName",usersVo.getCombination()).or().like("RealName",usersVo.getCombination()).eq("Eid",this.getLoginEnterpriseId()).eq("Grade",2).or().like("Phone",usersVo.getCombination()).eq("Eid",this.getLoginEnterpriseId()).eq("Grade",2);
		}
		Page<Users> page = new Page<>(usersVo.getPageIndex(), usersVo.getPageSize());
		IPage<Users> pageResult = userService.page(page, wrapper);
		result.setTotal((int)pageResult.getTotal());
		result.setData(pageResult.getRecords());
		return result;
	}


	@GetMapping("/getMenuByUserId/{userID}")
	@ResponseBody
	public	List<UserMenu> getMenuByUserId(@PathVariable(name = "userID") String userID) {
		QueryWrapper<UserMenu> userWrapper = new QueryWrapper<>();
		userWrapper.eq("UserID",userID);
		return userMenuService.list(userWrapper);
	}



	@GetMapping("/getById/{userID}")
	@ResponseBody
	public	Users getById(@PathVariable(name = "userID") String userID) {
		Users obj = userService.getById(userID);
		return obj;
	}

	@PostMapping("/save")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public ReturnVO save(@RequestBody Users users){
		ReturnVO result = new ReturnVO();
		QueryWrapper<Users> userWrapper = new QueryWrapper<>();
		userWrapper.eq("UserName",users.getUserName());
		if(userService.list(userWrapper).isEmpty() == false){
			result.setMessage("该登录账号已存在！");
			result.setCode("500");
			return result;
		}
		users.setPassword(DigestUtils.md5DigestAsHex(users.getPassword().getBytes()));
		users.setEid(this.getLoginEnterpriseId());
		Date date = new Date();
		String currentDateTime = CalendarDate.dateToStr(date,"yyyy-MM-dd HH:mm:ss");
		users.setCreateDateTime(currentDateTime);
		users.setGrade(2);
		users.setCreateName(getLoginUserName());
		//将自身的区域权限赋值给子账号
		Users users1 = userService.getById(this.getLoginUserId());
		if (users1 != null){
			users.setAuthTown(users1.getAuthTown());
			users.setAuthDistrict(users1.getAuthDistrict());
			users.setAuthCity(users1.getAuthCity());
			users.setUserType(users1.getUserType());
		}

		try {
			if(userService.save(users)){
				saveUserMenu(users);
				result.setMessage("保存成功！");
				result.setCode("200");
			}else{
				result.setMessage("保存失败！");
				result.setCode("500");
			}
		}catch (Exception e){
			log.error(e.getMessage());
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	private void saveUserMenu(Users users){
		QueryWrapper<UserMenu> wrapper = new QueryWrapper<>();
		wrapper.eq("UserId",users.getUserID());
		userMenuService.remove(wrapper);
		if(StringUtils.isEmpty(users.getUserMenuIds()) == false){
			String []items = users.getUserMenuIds().split(",");
			List<UserMenu> list = new ArrayList<>();
			for (String item:items
			) {
				UserMenu userMenu = new UserMenu();
				userMenu.setUserId(users.getUserID());
				userMenu.setMenuId(Integer.parseInt(item));
				list.add(userMenu);
			}
			userMenuService.saveBatch(list);
		}
	}

	@PostMapping("update")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public ReturnVO updateById(@RequestBody Users users){
		if (users.getPassword() != null && users.getPassword().equals("")){
			users.setPassword(null);
		}
		ReturnVO result = new ReturnVO();
		if(userService.updateById(users)){
			saveUserMenu(users);
			result.setMessage("保存成功！");
			result.setCode("200");
		}else{
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	@PostMapping("resetPwd")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public ReturnVO resetPwd(@RequestBody Users users){
		ReturnVO result = new ReturnVO();
		Users user = userService.getById(users.getUserID());
		user.setPassword(DigestUtils.md5DigestAsHex(users.getPassword().getBytes()));
		if(userService.updateById(user)){
			result.setMessage("操作成功！");
			result.setCode("200");
		}else{
			result.setMessage("操作失败！");
			result.setCode("500");
		}
		return result;
	}

	/**
     * 根据id删除
     */
	@DeleteMapping("/deleteById/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public ReturnVO deleteById(@PathVariable Serializable id) {
		ReturnVO result = new ReturnVO();
		QueryWrapper<UserMenu> wrapper = new QueryWrapper<>();
		wrapper.eq("UserId",id);
		userMenuService.remove(wrapper);
		if (userService.removeById(Integer.parseInt(id.toString())) == true) {
			result.setMessage("删除成功");
		} else {
			result.setMessage("删除失败");
			result.setCode("0");
		}
		return result;
	}

	@PostMapping("/enable/{id}")
	@ResponseBody
	public ReturnVO enable(@PathVariable Serializable id) {
		ReturnVO result = new ReturnVO();
		Users users = userService.getById(id);
		users.setActivity(1);
		if (userService.updateById(users)) {
			result.setMessage("操作成功");
		} else {
			result.setMessage("操作失败");
			result.setCode("0");
		}
		return result;
	}

	@PostMapping("/disable/{id}")
	@ResponseBody
	public ReturnVO disable(@PathVariable Serializable id) {
		ReturnVO result = new ReturnVO();
		Users users = userService.getById(id);
		users.setActivity(0);
		if (userService.updateById(users)) {
			result.setMessage("操作成功");
		} else {
			result.setMessage("操作失败");
			result.setCode("0");
		}
		return result;
	}

	/**
	 * 获得对应角色的子菜单
	 * @return
	 */
	@PostMapping("/getBreedSonMenu")
	@ResponseBody
	public ReturnVO getBreedSonMenu() {
		ReturnVO returnVO = new ReturnVO();

		QueryWrapper<RoleMenuVo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("rm.RoleID", getUserType()).eq("activity", 1);
		List<RoleMenuVo> roleMenuVos = roleMenuService.selectRoleMenuList(queryWrapper, null);

		if (roleMenuVos.size() > 0) {
			if ("3".equals(getUserType())){ //养殖
				//如果是猪1，移除产蛋记录，如果是鸡0，移除繁殖记录
				Iterator iterator = roleMenuVos.iterator();
				while (iterator.hasNext()){
					// 获得所有菜单
					RoleMenuVo roleMenuVo1 = (RoleMenuVo)iterator.next();
					if (getLoginAnimalTypes() == 1){ //猪，牛，羊
						if ("egg".equals(roleMenuVo1.getKeyName())){ //移除产蛋记录
							iterator.remove();
						}
					}
					if (getLoginAnimalTypes() == 0){ //养鸡，鸭...
						if ("reproductionManage".equals(roleMenuVo1.getKeyName())){ //移除繁殖记录
							iterator.remove();
						}
						if ("monthReportRecord".equals(roleMenuVo1.getKeyName())){ //移除月报管理
							iterator.remove();
						}
					}
					//移除养殖子菜单管理菜单
					if ("SonLoginYangzhi".equals(roleMenuVo1.getKeyName())){
						iterator.remove();
					}
					//移除企业管理
					if ("PersonalYangzhi".equals(roleMenuVo1.getKeyName())){
						iterator.remove();
					}
				}
			}
			if ("4".equals(getUserType())){ //屠宰
				Iterator iterator = roleMenuVos.iterator();
				while (iterator.hasNext()){
					// 获得所有菜单
					RoleMenuVo roleMenuVo1 = (RoleMenuVo)iterator.next();

					//移除屠宰子菜单管理菜单
					if ("SonLoginTuzai".equals(roleMenuVo1.getKeyName())){
						iterator.remove();
					}
					//移除企业管理
					if ("PersonalTuzai".equals(roleMenuVo1.getKeyName())){
						iterator.remove();
					}
				}
			}
			if ("5".equals(getUserType())){ //无害化处理
				Iterator iterator = roleMenuVos.iterator();
				while (iterator.hasNext()){
					// 获得所有菜单
					RoleMenuVo roleMenuVo1 = (RoleMenuVo)iterator.next();

					//移除无害化处理子菜单管理菜单
					if ("SonLoginWuhai".equals(roleMenuVo1.getKeyName())){
						iterator.remove();
					}
				}
			}
			returnVO.setCode("200");
			Map<String, Object> map = new HashMap<>();
			List<LinkedHashMap<String,Object>> linkedHashMaps=new ArrayList<>();
			for(RoleMenuVo roleMenuVo:roleMenuVos){
				LinkedHashMap<String,Object> stringObjectLinkedHashMap=new LinkedHashMap<>();
				stringObjectLinkedHashMap.put("menuId",roleMenuVo.getId());
				stringObjectLinkedHashMap.put("textCH",roleMenuVo.getTextCH());
				linkedHashMaps.add(stringObjectLinkedHashMap);
			}
			map.put("Menus", linkedHashMaps);
			returnVO.setData(map);
		} else
			returnVO.setCode("503");
		return returnVO;
	}
}
